﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Green.FastInvoker;
using Green.Utility;

namespace Green.AgileMapper
{
    [Serializable]
    public class SimpleMappingRule : IMappingRule, IXmlConfigLoad
    {
        public string FromPoperty
        { get; private set; }

        public string ToPoperty
        { get; private set; }

        public bool IsConvertTo
        { get; private set; }

        public bool IsConvertFrom
        { get; private set; }

        public SimpleMappingRule(string fromPoperty, string toPoperty, bool isConvertTo, bool isConvertFrom)
        {
            this.FromPoperty = fromPoperty;
            this.ToPoperty = toPoperty;
            this.IsConvertFrom = isConvertFrom;
            this.IsConvertTo = isConvertTo;
        }

        public SimpleMappingRule(string fromPoperty, string toPoperty)
            : this(fromPoperty, toPoperty, true, true)
        { }

        public SimpleMappingRule()
        {
        }

        #region IMappingRule 成员
        /// <summary>
        /// 根据 To得到From
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        public virtual void WarpFrom(object from, object to)
        {
            if (IsConvertFrom)
            {
                var value = PropertyAccessor.Get(to, this.ToPoperty);

                value = value.ChangeType(PropertyAccessor.GetPropertyType(from, this.FromPoperty));

                PropertyAccessor.Set(from, this.FromPoperty, value);

            }
        }
        /// <summary>
        /// 根据From得到To
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        public virtual void WarpTo(object from, object to)
        {
            if (IsConvertTo)
            {
                var value = PropertyAccessor.Get(from, this.FromPoperty);
                value = value.ChangeType(PropertyAccessor.GetPropertyType(to, this.ToPoperty));

                PropertyAccessor.Set(to, this.ToPoperty, value, true);


            }
        }

        #endregion

        #region IXmlConfigLoad 成员

        public void LoadXmlConfig(Dictionary<string, object> propertys)
        {
            this.FromPoperty = propertys.TryGetValue<string, string>("FromPoperty", string.Empty);
            this.ToPoperty = propertys.TryGetValue<string, string>("ToPoperty", string.Empty);
            this.IsConvertTo = propertys.TryGetValue<string, bool>("IsConvertTo", true);
            this.IsConvertFrom = propertys.TryGetValue("IsConvertFrom", true);
        }

        #endregion
    }
}
